var quotas = [
      {quotaCategory:'产能',
       quotaItems:[
                   {quotaCode:"CMI",
            	    quotaDesc:"CMI值",
            	    chartType:"",
            	    quotaClass:"均值类",
            	    relatedQuota:[
            	                  {quotaCode:"InCaseCnt",quotaDesc:"入组病例数"},
            	                  {quotaCode:"TotalWeight",quotaDesc:"总权重"}
            	                 ]
                   },
                   {quotaCode:"DRGCount",
                	quotaDesc:"DRGs组数",
                	chartType:"pie",
                	relatedQuota:[
                	              {quotaCode:"InCaseCnt",quotaDesc:"入组病例数"},
                	              {quotaCode:"CMI",quotaDesc:"CMI值"},
                	              {quotaCode:"TotalWeight",quotaDesc:"总权重"},
                	              {quotaCode:"KeyDRGCnt",quotaDesc:"重点病组数"},
                	              {quotaCode:"KeyDRGRatio",quotaDesc:"重点病组占比（%）"},
                	              {quotaCode:"ValidDRGCnt",quotaDesc:"有效DRGs组数"},
                	              {quotaCode:"ValidDRGs",quotaDesc:"有效DRGs占比（%）"}
                	              ]
                   },
                   {quotaCode:"TotalWeight",
                	quotaDesc:"总权重",
                	quotaClass:"求和类",
                	relatedQuota:[
                	              {quotaCode:"InCaseCnt",quotaDesc:"入组病例数"},
                	              {quotaCode:"DRGCount",quotaDesc:"DRGs组数"},
                	              {quotaCode:"CMI",quotaDesc:"CMI值"}
                	             ]
                   },
                   {quotaCode:"WeightPerDoctor",
                   	quotaDesc:"每医师权重",
                   	quotaClass:"均值类",
                   	relatedQuota:[
                   	              {quotaCode:"InCaseCnt",quotaDesc:"入组病例数"},
                   	              {quotaCode:"",quotaDesc:"额定医师数"}
                   	             ]
                   },
                   {quotaCode:"WeightPerBedDays",
                  	quotaDesc:"每床位权重",
                  	quotaClass:"均值类",
                  	relatedQuota:[
                  	              {quotaCode:"InCaseCnt",quotaDesc:"入组病例数"},
                  	              {quotaCode:"",quotaDesc:"编制床位数"}
                  	             ]
                    }
                  ]
      },
      {quotaCategory:'效率',
       quotaItems:[
                   {quotaCode:"TimeEff",
                	quotaDesc:"时间消耗指数",
                	quotaClass:"均值类",
                	relatedQuota:[
                	              {quotaCode:"InCaseCnt",quotaDesc:"入组病例数"},
                	              {quotaCode:"DRGAvgDays",quotaDesc:"DRG平均住院日"},
                	              {quotaCode:"DRGTotalDays",quotaDesc:"DRG总住院日"}
                	             ]
                   },
                   {quotaCode:"FeeEff",
                	quotaDesc:"费用消耗指数",
                	quotaClass:"均值类",
                	relatedQuota:[
                	              {quotaCode:"InCaseCnt",quotaDesc:"入组病例数"},
                	              {quotaCode:"DRGAvgFee",quotaDesc:"DRG次均费用"},
                	              {quotaCode:"DRGTotalFee",quotaDesc:"DRG总费用"}
                	             ]
                   },
                   {quotaCode:"BaseFee",
                	quotaDesc:"住院患者基本费率",
                	quotaClass:"比率类",
                	relatedQuota:[
                	              {quotaCode:"TotalFee",quotaDesc:"总费用"},
                	              {quotaCode:"TotalWeight",quotaDesc:"总权重"}
                	             ]
                   }
                  ]
      },
      {quotaCategory:'安全',
       quotaItems:[
                   {quotaCode:"Risk1DeadCaseCnt",
                	quotaDesc:"低风险死亡人数",
                	quotaClass:"求和类",
                	relatedQuota:[
                	              {quotaCode:"Risk1Ratio",quotaDesc:"低风险死亡率（%）"},
                	              {quotaCode:"Risk1DeadCaseCnt",quotaDesc:"低风险人数"},
                	              {quotaCode:"InCaseCnt",quotaDesc:"入组病例数"}
                	             ]
                   },
                   {quotaCode:"Risk2DeadCaseCnt",
                	quotaDesc:"中低风险死亡人数",
                	quotaClass:"求和类",
                	relatedQuota:[
                	              {quotaCode:"Risk2Ratio",quotaDesc:"中低风险死亡率（%）"},
                	              {quotaCode:"Risk2DeadCaseCnt",quotaDesc:"中低风险人数"},
                	              {quotaCode:"InCaseCnt",quotaDesc:"入组病例数"}
                	             ]
                   },
                   {quotaCode:"Risk3CureRatio",
                	quotaDesc:"中高风险治愈率（%）",
                	quotaClass:"比率类",
                	relatedQuota:[
                	              {quotaCode:"Risk3CureCaseCnt",quotaDesc:"中高风险治愈人数"},
                	              {quotaCode:"Risk3DeadCaseCnt",quotaDesc:"中高风险死亡人数"},
                	              {quotaCode:"Risk3DeadRatio",quotaDesc:"中高风险死亡率（%）"},
                	              {quotaCode:"Risk3CaseCnt",quotaDesc:"中高风险人数"},
                	              {quotaCode:"InCaseCnt",quotaDesc:"入组病例数"}
                	             ]
                   },
                   {quotaCode:"Risk4CureRatio",
                	quotaDesc:"高风险治愈率（%）",
                	quotaClass:"比率类",
                	relatedQuota:[
                	              {quotaCode:"Risk4CureCaseCnt",quotaDesc:"高风险治愈人数"},
                	              {quotaCode:"Risk4DeadCaseCnt",quotaDesc:"高风险死亡人数"},
                	              {quotaCode:"Risk4DeadRatio",quotaDesc:"高风险死亡率（%）"},
                	              {quotaCode:"Risk4CaseCnt",quotaDesc:"高风险人数"},
                	              {quotaCode:"InCaseCnt",quotaDesc:"入组病例数"}
                	             ]
                   }
                  ]
      },
      {quotaCategory:'出院人数',
       quotaItems:[
                   {quotaCode:"InCaseCnt",
                	quotaDesc:"入组病例数",
                	quotaClass:"求和类",
                	relatedQuota:[
                	              {quotaCode:"TotalCaseCnt",quotaDesc:"出院病例数"},
                	              {quotaCode:"Over60DaysCaseCnt",quotaDesc:"大于60病例数"},
                	              {quotaCode:"NotInCaseCnt",quotaDesc:"未入组病例数"},
                	              {quotaCode:"InRatio",quotaDesc:"入组率（%）"}
                	             ]
                   },
                   {quotaCode:"CureCnt",
                	quotaDesc:"治愈好转人数",
                	quotaClass:"求和类",
                	chartType:"",
                	relatedQuota:[
                	              {quotaCode:"CureCnt",quotaDesc:"治愈好转率（%）"},
                	              {quotaCode:"DeadRatio",quotaDesc:"死亡率（%）"},
                	              {quotaCode:"DeadCaseCnt",quotaDesc:"死亡人数"},
                	              {quotaCode:"OutWay1Cnt",quotaDesc:"医嘱离院病例数"},
                	              {quotaCode:"OutWay2Cnt",quotaDesc:"医嘱转院病例数"},
                	              {quotaCode:"OutWay3Cnt",quotaDesc:"医嘱转社区病例数"},
                	              {quotaCode:"OutWay4Cnt",quotaDesc:"非医嘱离院病例数"}
                	             ]
                   }
                  ]
      },
      {quotaCategory:'费用',
       quotaItems:[
                   {quotaCode:"TotalFee",
                	quotaDesc:"总费用",
                	quotaClass:"求和类",
                	relatedQuota:[
                	              {quotaCode:"TotalCaseCnt",quotaDesc:"出院病例数"},
                	              {quotaCode:"DrugFee",quotaDesc:"药品费用"},
                	              {quotaCode:"DrugRatio",quotaDesc:"药占比（%）"},
                	              {quotaCode:"MaterialFee",quotaDesc:"材料费用"},
                	              {quotaCode:"MaterialRatio",quotaDesc:"材料占比（%）"}
                	             ]
                   },
                   {quotaCode:"AvgFee",
                   	quotaDesc:"次均费用",
                   	quotaClass:"均值类",
                   	relatedQuota:[
                   	              {quotaCode:"TotalFee",quotaDesc:"总费用"},
                   	              {quotaCode:"TotalCaseCnt",quotaDesc:"出院病例数"}
                   	             ]
                   }
                  ]
      }
];
var filterCharts={};
var filterTrendCharts={};
var showOrNot = true;

var compareName = '';//同期 | 上期 ……
var compareName1 = '';//同期比 | 上期比 ……
var compareText='增长率';//根据指标类型：增长率  | 增长量

//加载查询条件
/**
 * benchmark标杆
 * mrType周期
 * yearCon年份
 * qom季度|月份
 */	
var tabId;
function queryLoad(benchmark,mrType,yearCon,qom,pType){
	//滚动条默认最上面
	//scrollTo(0,0);
	tabId=$("#tabContent > .tab-pane.active").attr("id");
	//获取当前选中tab页的tabId
	$("#navTabs").find("li").each(function(i){
		$(this).on("click", function () {
			scrollTo(0,0);
			tabId=$("#tabContent > .tab-pane.active").attr("id");
         });
	});
	
	//修改tab标签页href
	$("#"+tabId+" ul > li a").each(function(){
		$(this).attr("href",$(this).attr("href")+tabId);//赋值
	});
	
	//修改tab内容页ID
	$("#"+tabId+" .tab-content div[role='tabpanel']").each(function(){
		$(this).attr("id",$(this).attr("id")+tabId);//赋值
	});
	
	//获取最近一次监测时间
	$.ajax({
		url:contextPath+'/MonitorResult/findMrDatetoRecently.dhc',
		type:"post",
		dataType:"json",
		async:false,
		success:function(result){
			var mrDateto = result.data;
			 var arr= new Array();
			 arr=mrDateto.split("-");
			 $("#"+tabId+" #initYear").attr("value",arr[0]);//填充内容 
			 $("#"+tabId+" #initMonth").attr("value",arr[1]);//填充内容
			 
			year = parseInt(arr[0]);
			month = parseInt(arr[1]);
			var lastY = year - 1;
			var blastY = year - 2;
			$('#'+tabId+' #mrYear').html('<option value="'+year+'" selected="selected">'+year+'年</option>'
					+'<option value="'+lastY+'">'+lastY+'年</option>'
					+'<option value="'+blastY+'" >'+blastY+'年</option>'
					);
//			$('#'+tabId+' #mrDate option').eq(month-1).attr('selected','true');
//			mrDate();
//			$('#'+tabId+' #mrYear option [value="'+year+'"]').attr('selected','true');
			$('#'+tabId+' #mrDate option').eq(month-1).attr('selected','true');
 			if(typeof(paramTabPage[tabId]) == "undefined"){
				if(typeof(data) == "undefined"){
					paramTabPage[tabId]={};
				}else{
					paramTabPage[tabId]=data;
				}
			}
			loadParam(benchmark,mrType,yearCon,qom,pType);
		}
	})
}

//初始化界面条件参数
function loadParam(benchmark,mrType,yearCon,qom,pType){
	if(""!=benchmark&&""!=mrType&&""!=yearCon&&""!=qom&&""!=pType){
		
		//旧版赋值语句
//		$('#'+tabId+' #benchmark option[value='+benchmark+']').attr('selected','true');
//		$('#'+tabId+' #mrType option[value='+mrType+']').attr('selected','true');
		
		//上层钻取赋值
		$('#'+tabId+' #benchmark').val(benchmark);
		$('#'+tabId+' #mrType').val(mrType);
		$('#'+tabId+' #patientType').val(pType);
		
		//修改选择框选择状态
		$('#'+tabId+' .s-row a[data-type="compare"]').removeClass('curr');
		$('#'+tabId+' .s-row a[data-type="period"]').removeClass('curr');
		$('#'+tabId+' .s-row a[data-type="personType"]').removeClass('curr');
		$('#'+tabId+' .s-row a[data-value="'+benchmark+'"]').addClass('curr');
		$('#'+tabId+' .s-row a[data-value="'+mrType+'"]').addClass('curr');
		$('#'+tabId+' .s-row a[data-value="'+pType+'"]').addClass('curr');
		
//		mrDate();
		$('#'+tabId+' #mrYear option[value='+yearCon+']').attr('selected','true');
		$('#'+tabId+' #mrDate option[value='+qom+']').attr('selected','true');
	}
	else {
		
		//旧版赋值语句
		//$('#'+tabId+' #mrType option[value="MC"]').attr('selected','true');
		
		//赋值
		$('#'+tabId+' #mrType').val('MC');
		
		//修改显示状态
		$('#'+tabId+' .s-row a[data-type="period"]').removeClass('curr');
		$('#'+tabId+' .s-row a[data-value="MC"]').addClass('curr');
	}
}

//所有图表添加正在加载图层
function loading(){
	//使用同一加载标志现在暂时注释掉
	/*$("#"+tabId+" div[id*='-table']").each(function(){
		$(this).html("<image src='"+contextPath+"/images/pageloading.gif' />");
	}); 
	$("#"+tabId+" div[id*='-chart']").each(function(){
		$(this).html("<image src='"+contextPath+"/images/pageloading.gif' />");
	}); */
}
//
////切换标杆
//$("#"+tabId+" #benchmark").change(function(){
//	checkMrType();
//})
//
////切换周期
//$("#"+tabId+" #mrType").change(function(){
////	mrDate();
//	checkMrType();
//})
//
////切换年份
//$("#"+tabId+" #mrYear").change(function(){
////	mrDate();
//})
//
////切换标杆
//function changeStd(){
//	var mrType=$('#mrType').val();
////	mrDate();
//	checkMrType();
//}

//选择条件改变是刷新数据
function conditionChange(){
	var benchmark=$('#'+tabId+' #benchmark').val();//标杆
	var mrType = $('#'+tabId+' #mrType').val();//周期
	var yearCon = $('#'+tabId+' #mrYear').val();//年份
	var qom = $('#'+tabId+' #mrDate').val();//月份
	var pType = $('#'+tabId+' #patientType').val();//季度|月份
	var mrLot = yearCon + "Y" + qom + mrType;
	var pType = $('#'+tabId+' #patientType').val();
	paramTabPage[tabId].yearCon=yearCon;
	paramTabPage[tabId].qom=qom;
	paramTabPage[tabId].mrLot=mrLot;
	paramTabPage[tabId].mrType=mrType;
	paramTabPage[tabId].benchmark=benchmark;
	paramTabPage[tabId].pType=pType;
	
	
	if(pType=='0'){
		$('#'+tabId+' #queryInfo_person').html('全院出院病例');
	} else {
		$('#'+tabId+' #queryInfo_person').html('医保出院病例');
	}
	
	if(mrType=='MC'){
		$('#'+tabId+' #queryInfo_time').html(yearCon+'年1月~'+yearCon+'年'+qom+'月');
	} else {
		$('#'+tabId+' #queryInfo_time').html(yearCon+'年'+qom+'月');
	}
	
	if (benchmark=='year'){
		$('#'+tabId+' #queryInfo_compare').html('同比');
	} else if(benchmark=='month'){
		$('#'+tabId+' #queryInfo_compare').html('环比');
	} else if(benchmark=='manage'){
		$('#'+tabId+' #queryInfo_compare').html('绩效比');
	} else if(benchmark=='std'){
		$('#'+tabId+' #queryInfo_compare').html('标杆比');
	}
}

//检查周期类型
//function checkMrType(){
//	if ($('#'+tabId+' #mrType').val()=='MC') {
//		$('#'+tabId+' #mrDate').css('display','none');
////		$("#benchmark option").eq(0).attr('selected', 'true');
//		$("#"+tabId+" #benchmark option").eq(1).attr('disabled','disabled');
//	} else {
//		$('#'+tabId+' #mrDate').css('display','block');
//		$("#"+tabId+" #benchmark option").eq(1).removeAttr('disabled');
//	}
//}

//条件级联
//function mrDate(){
//	if ($('#'+tabId+' #mrType').val()=='M') {
//		$('#'+tabId+' #mrDate').html('<option value="1">1月</option>'
//				+'<option value="2">2月</option>'
//				+'<option value="3">3月</option>'
//				+'<option value="4">4月</option>'
//				+'<option value="5">5月</option>'
//				+'<option value="6">6月</option>'
//				+'<option value="7">7月</option>'
//				+'<option value="8">8月</option>'
//				+'<option value="9">9月</option>'
//				+'<option value="10">10月</option>'
//				+'<option value="11">11月</option>'
//				+'<option value="12">12月</option>');
//	}else if ($('#'+tabId+' #mrType').val()=='Q') {
//		$('#'+tabId+' #mrDate').html('<option value="1" selected="selected">1季度</option>'
//				+'<option value="2">2季度</option>'
//				+'<option value="3">3季度</option>'
//				+'<option value="4">4季度</option>');
//	}else if ($('#'+tabId+' #mrType').val()=='MC') {
//		var yearPage = $('#'+tabId+' #mrYear').val();
//		if(yearPage==year){
//			$('#'+tabId+' #mrDate').html('<option value="'+month+'" selected="selected">'+month+'月</option>');
//		}else{
//			$('#'+tabId+' #mrDate').html('<option value="12" selected="selected">12月</option>');
//		}
//	}
//}

//隐藏和显示mrDate框
function showOrhide(){
	if($('#'+tabId+' #mrType').val()=='MC'){
		$('#'+tabId+' #mrDate').hide();
	}else{
		$('#'+tabId+' #mrDate').show();
	}
}


//展开日期标杆
function opc1(){
	if ($('#'+tabId+' #date_div').css('position')=='fixed') {
		$('#'+tabId+' #date_div').css({'opacity':'1','z-index':'99996','transform':'perspective(400px) rotateY(0deg)'});
	}
}
//收起日期标杆
function opc0(){
	if ($('#'+tabId+' #date_div').css('position')=='fixed') {
		$('#'+tabId+' #date_div').css({'opacity':'1','transform':'perspective(400px) rotateY(-70deg)'});
	}
}
//页面跳转
function DRGtarget(type){
	$("html,body").animate({scrollTop:$("#"+tabId+" #"+type+"").offset().top-170}, 500);
}

//展开收起
function heightMore(){
	if($('#'+tabId+' #upDown').css('height')=='130px'){
		$('#'+tabId+' #upDown').css({'height':'400px','border-bottom-color':'#fff','overflow-y':'visible'});
	}else {
		$('#'+tabId+' #upDown').css({'height':'130px','border-bottom-color':'#ddd','overflow-y':'hidden'});
	}
}

//趋势图
function openTrendTable(ccode,ddesc,quotaCate,tfrom,depGroupCode,depCode,groupName,mdcCode,adrgCode,drgCode,mrLot,mrType,benchmark){
	if(tfrom=="depGroup"){
		depGroupCode=ccode;
	}else if(tfrom=="dep"){
		depCode=ccode;
	}else if(tfrom=="MDC"){
		mdcCode=ccode;
	}else if(tfrom=="ADRG"){
		adrgCode=ccode;
	}else if(tfrom=="DRG"){
		drgCode=ccode;
	}else{
		ccode="DRG_DHCC";
	}
	topDialog();
	var quotas;
	var ulstr='';
	var divstr='';
	ulstr+='<ul class="nav nav-tabs" role="tablist" style="border-color: #5FBF18;">';
	divstr+='<div class="tab-content" >';
	if(quotaCate=="key"){
		$('#'+tabId+' #pop-title').html("医保重点监测指标趋势信息");
		quotas=[{"quotaCode": "HCCaseCnt", "quotaDesc": "医保人数"}, {"quotaCode": "HCTotalFee", "quotaDesc": "医保总费用"}, {"quotaCode": "HCAvgFee", "quotaDesc":"医保次均费用"}]
	}else if(quotaCate=="other"){
		$('#'+tabId+' #pop-title').html("医保相关其他指标趋势信息");
		quotas=[{"quotaCode": "HCTotalFund", "quotaDesc": "医保总基金"}, {"quotaCode": "HCDrugFee", "quotaDesc": "医保总药品费用"}, {"quotaCode": "HCDrugRatio", "quotaDesc":"医保药占比"}]
	}else if(quotaCate=="common"){
		$('#'+tabId+' #pop-title').html("医保常规总体指标趋势信息");
		quotas=[{"quotaCode": "TotalCaseCnt", "quotaDesc": "出院人数"}, {"quotaCode": "AvgDays", "quotaDesc": "平均住院日"}, {"quotaCode": "AvgFee", "quotaDesc":"次均费用"}, {"quotaCode": "TotalFee", "quotaDesc": "总费用"}, {"quotaCode": "DrugRatio", "quotaDesc": "药占比"}, {"quotaCode": "MaterialRatio", "quotaDesc":"耗占比"}]
	}else if(quotaCate=="cap"){
		$('#'+tabId+' #pop-title').html("产能各指标趋势信息");
		quotas=[{"quotaCode": "CMI", "quotaDesc": "CMI"}, {"quotaCode": "DRGCount", "quotaDesc": "DRGs组数"}, {"quotaCode": "TotalWeight", "quotaDesc":"总权重"}, {"quotaCode": "InCaseCnt", "quotaDesc": "入组病例数"}]
	}else if(quotaCate=="eff"){
		$('#'+tabId+' #pop-title').html("效率各指标趋势信息");
		quotas=[{"quotaCode": "TimeEff", "quotaDesc": "时间消耗指数"}, {"quotaCode": "FeeEff", "quotaDesc": "费用消耗指数"}, {"quotaCode": "WeightPerDoctor", "quotaDesc":"每医师权重"}, {"quotaCode": "WeightPerBedDays", "quotaDesc": "每床日权重"}]
	}else if(quotaCate=="qua"){
		$('#'+tabId+' #pop-title').html("安全各指标趋势信息");
		quotas=[{"quotaCode": "Risk1Ratio", "quotaDesc": "低风险死亡率"}, {"quotaCode": "Risk2Ratio", "quotaDesc": "中低风险死亡率"}];
	}else{
		$('#'+tabId+' #pop-title').html("医院各指标趋势信息");
		quotas=[{"quotaCode": "TotalWeight", "quotaDesc": "总权重"}, {"quotaCode": "AvgDays", "quotaDesc": "平均住院日"}, {"quotaCode": "AvgFee", "quotaDesc": "次均费用"}];
	}
	for(var i=0; i<quotas.length; i++){
		if(i==0){
			ulstr+='<li class="active">';
			divstr+='<div role="tabpanel" class="tab-pane fade active in" id="poptab-'+i+'">'
		}else{
			ulstr+='<li>';
			divstr+='<div role="tabpanel" class="tab-pane fade in" id="poptab-'+i+'">';
		}
		ulstr+='<a class="tabActive" href="#poptab-'+i+'" role="tab" data-toggle="tab">'
		ulstr+=quotas[i].quotaDesc;
		ulstr+='</a>';
		ulstr+='</li>';
		divstr+='<div id="pop'+quotas[i].quotaCode+'-chart" style="width: ;"></div>'
		divstr+='</div>';
	}
	ulstr+='</ul>';
	
	$('#'+tabId+' #pop-body').html('');
	$('#'+tabId+' #pop-body').html(ulstr+divstr);
	for(var i=0; i<quotas.length; i++){
		$.post(contextPath+'/MonitorResult/getTrendList.dhc', 
				{'mrLot':mrLot, 
				 'mrType':mrType,
				 'mrStdtype':benchmark,
				 'ccode': quotas[i].quotaCode,
				 'ddesc': quotas[i].quotaDesc,
				 'desc': ddesc,
				 'pardepCode':depCode,
				 'pardepgroupCode':depGroupCode,
				 'pargroupName': groupName,
				 'parmdcCode':mdcCode,
				 'paradrgCode': adrgCode,
				 'pardrgCode': drgCode}).done(function(result){
					var chart=result.data;
					$('#'+tabId+' #pop'+chart.ccode+'-chart').highcharts(chart.chartJson);
				 });
	}
}

//获取所有月份的指标值（用于趋势图）
function getTrendChartData(pType,depGroupCode,depCode,groupName,mdcCode,adrgCode,drgCode,loadType,firstQuota){
	    var trendChartData=null;
		$.ajax({
				type: "post",
			   cache: false, 
			   async: false, //同步
				 url: contextPath+'/MonitorResult/findAllMonthData.dhc', 
				data: {
						 'pardepgroupCode':depGroupCode,
						 'pardepCode':depCode,
						 'pargroupName': groupName,
						 'parmdcCode':mdcCode,
						 'paradrgCode': adrgCode,
						 'pardrgCode': drgCode,
						 'type1':loadType,
						 'quotaCode':firstQuota,
						 'pType':pType
					  },
			 success: function(result){
						trendChartData = result.data;
			 		  }
		});
		return trendChartData;
}

//比较两个数值，返回升降率
function compareValueGrowPer(thisYearValue,lastYearValue){	
	var ty=thisYearValue;
	var ly=lastYearValue;
	if(isNaN(parseInt(ty)) || isNaN(parseInt(ly))){
		return '';
	}
	var result='';
	if(ly == 0){
		return '--';
	}else if (ty>ly) {
		if (ty != 0) {
			result=((ty-ly)*100/ly).toFixed(2);
		}else {
			result='';
		}
		return '<span style="color:red;"><i class="glyphicon glyphicon-arrow-up"></i>'+result+'%</span>';
	} else if(ty<ly){
		if (ty != 0) {
			result=((ly-ty)*100/ly).toFixed(2);
		}else {
			result='';
		}
		return '<span style="color:green;"><i class="glyphicon glyphicon-arrow-down"></i>'+result+'%</span>';
	}else if(ty==ly){
		return '<span style="color:orange;"><i class="glyphicon glyphicon-minus"></i>0</span>';
	}
}

//比较两个数值，返回升降值
function compareValueGrowNum(thisYearValue,lastYearValue){	
	var ty=thisYearValue;
	var ly=lastYearValue;
	if(isNaN(parseInt(ty)) || isNaN(parseInt(ly))){
		return '';
	}
	var result='';
	if (ty>ly) {
		if (parseInt(ty-ly)==(ty-ly)) {
			result=(ty-ly)
		}else {
			result=(ty-ly).toFixed(2);
		}
		return '<span style="color:red;"><i class="glyphicon glyphicon-arrow-up"></i>'+result+'</span>';
	} else if(ty<ly){
		if (parseInt(ly-ty)==(ly-ty)) {
			result=ly-ty
		}else {
			result=(ly-ty).toFixed(2);
		}
		return '<span style="color:green;"><i class="glyphicon glyphicon-arrow-down"></i>'+result+'</span>';
	}else if(ty==ly){
		return '<span style="color:orange;"><i class="glyphicon glyphicon-minus"></i>0%</span>';
	}
}

//获取指标值，增长量，增幅的最大最小值的Div
function getQuotaMaxMinDiv(tableData,quotaCode,quotaDesc,compareName1){
	var maxName1 = '',minName1 = '',maxValue1 = -Infinity,minValue1 = Infinity;//本期值比较
	var maxName2 = '',minName2 = '',maxValue2 = -Infinity,minValue2 = Infinity;//增长量比较
	var maxName3 = '',minName3 = '',maxValue3 = -Infinity,minValue3 = Infinity;//增幅比较
	
	var hasData = false;
	var hasCompareData = false;
	$.each(tableData,function(i,data){
		hasData = true;
		if (data['compare'+quotaCode] != undefined) {
			hasCompareData = true;
		}
		
		//指标值比较
		if (data[quotaCode]>maxValue1) {
			maxValue1 = data[quotaCode];
			maxName1 = data.ddesc;
		}
		if (data[quotaCode]<minValue1) {
			minValue1 = data[quotaCode];
			minName1 = data.ddesc;
		}
		
		//增长量比较
		if ((data[quotaCode] - data['compare'+quotaCode])>maxValue2) {
				maxValue2 = (data[quotaCode] - data['compare'+quotaCode]).toFixed(2);
				maxName2 = data.ddesc;
			}
		if ((data[quotaCode] - data['compare'+quotaCode])<minValue2) {
			minValue2 = (data[quotaCode] - data['compare'+quotaCode]).toFixed(2);
			minName2 = data.ddesc;
		}
		if(Math.abs(maxValue2) == Infinity || Math.abs(minValue2) == Infinity){
			maxValue2 = "-";
			minValue2 = "-";
		}
		
		//增幅比较
		if (((data[quotaCode] - data['compare'+quotaCode])*100/data['compare'+quotaCode])>maxValue3) {
			maxValue3 = ((data[quotaCode] - data['compare'+quotaCode])*100/data['compare'+quotaCode]).toFixed(4);
			maxName3 = data.ddesc;
		}
		if (((data[quotaCode] - data['compare'+quotaCode])*100/data['compare'+quotaCode])<minValue3) {
			minValue3 = ((data[quotaCode] - data['compare'+quotaCode])*100/data['compare'+quotaCode]).toFixed(2);
			minName3 = data.ddesc;
		}
		if(data[quotaCode] == data['compare'+quotaCode]) {
			minValue3=0;
		}
		if(Math.abs(maxValue3) == Infinity || Math.abs(minValue3) == Infinity){
			maxValue3 = "-";
			minValue3 = "-";
		}
	})
	
	if (!hasData) {
		maxValue1='';
		minValue1='';
		maxValue2='';
		minValue2='';
		maxValue3='';
		minValue3='';
	}
	if (!hasCompareData) {
		maxValue2='';
		minValue2='';
		maxValue3='';
		minValue3='';
	}
	
	return '  <div class="col-md-4 quota-maxmin">'
			+'	  <div>'
			+'		<h5>'+quotaDesc+'本期值</h5>'
			+'		<div>最高值：<span>'+ maxName1 +'（'+ maxValue1 +'）</span></div>'
			+'		<div>最低值：<span>'+ minName1 +'（'+ minValue1 +'）</span></div>'
			+'	  </div>'
			+'  </div>'
			+'  <div class="col-md-4 quota-maxmin">'
			+'	  <div>'
			+'		<h5>'+compareName1+'增长量</h5>'
			+'		<div>最高值：<span>'+ maxName2 +'（'+ (maxValue2) +'）</span></div>'
			+'		<div>最低值：<span>'+ minName2 +'（'+ (minValue2) +'）</span></div>'
			+'	  </div>'
			+'  </div>'
			+'  <div class="col-md-4 quota-maxmin">'
			+'	  <div>'
			+'		<h5>'+compareName1+'增幅</h5>'
			+'		<div>最高值：<span>'+ maxName3 +'（'+ maxValue3 +'%）</span></div>'
			+'		<div>最低值：<span>'+ minName3 +'（'+ minValue3 +'%）</span></div>'
			+'	  </div>'
			+'  </div>';
}

//加载可翻页的趋势图
function loadTrendCharts(trendChartData,quotaCode,quotaDesc){
	var resultList = trendChartData.resultList;
	var category = trendChartData.categories;
	
	var totalMonthNum = category.length;//总月份数
	var startMonthIndex = 0;//起始下标
	var endMonthIndex = 0;//结束下标
	
	//计算下标
	if(totalMonthNum>6){
		startMonthIndex = totalMonthNum-6;
		endMonthIndex = totalMonthNum;
	}else {
		startMonthIndex = 0;
		endMonthIndex = totalMonthNum;
	}
	
	//截取数组
	var chart = {};
	var series = [];
	$('#'+tabId+' a[data-quota="'+quotaCode+'"]').attr('data-endIndex',endMonthIndex);
	var categories = category.slice(startMonthIndex,endMonthIndex);
	for (var i = 0; i < resultList.length; i++) {
		for ( var key in resultList[i]) {
			var monthData = resultList[i][key].slice(startMonthIndex,endMonthIndex);
			var data = [];
			for (var j = 0; j < monthData.length; j++) {
				data[j] = Number(monthData[j][quotaCode]);
			}
			series[i] = {name:key,data:data};
		}
	}
	
	chart['title'] = quotaDesc + '近'+categories.length+'个月趋势图';
	chart['series'] = series;
	chart['categories'] = categories;
	chart['yTitle'] = quotaDesc;
	
	$('#'+tabId+' #'+quotaCode+'_trend_chart').lineChart(chart);
}

//趋势图绑定向前向后的事件
function bindTrendChartEvent(){
	var showNum = 6;//每页显示数据条数
	//向前按钮
	$('a.prevMonth[data-quota]').on('click',function(){
		var quotaCode = $(this).attr('data-quota');
		var quotaDesc = $(this).attr('data-quotaDesc');
		var endIndex = $(this).attr('data-endIndex');
		
		var resultList = filterTrendCharts.resultList;
		var category = filterTrendCharts.categories;
		
		var totalMonthNum = category.length;//总月份数
		var startMonthIndex = 0;//起始下标
		var endMonthIndex = Number(endIndex);//结束下标
		
		//计算下标
		if(totalMonthNum>showNum){
			if(endMonthIndex-(showNum*2)>=0){
				startMonthIndex = endMonthIndex-(showNum*2);
				endMonthIndex -= showNum;
			} else if(endMonthIndex > showNum){
				endMonthIndex -= showNum;
			} else {
				return;
			}
		}else {
			return;
		}
		
		//截取数组
		var chart = {};
		var series = [];
		$('#'+tabId+' a[data-endIndex][data-quota="'+quotaCode+'"]').attr('data-endIndex',endMonthIndex);
		var categories = category.slice(startMonthIndex,endMonthIndex);
		for (var i = 0; i < resultList.length; i++) {
			for ( var key in resultList[i]) {
				var monthData = resultList[i][key].slice(startMonthIndex,endMonthIndex);
				var data = [];
				for (var j = 0; j < monthData.length; j++) {
					data[j] = Number(monthData[j][quotaCode]);
				}
				series[i] = {name:key,data:data};
			}
		}
		
		chart['title'] = quotaDesc + '趋势图';
		chart['subtitle'] = categories[0].replace(/-0|-/,'年') +'月——'+ categories[categories.length-1].replace(/-0|-/,'年') +'月';
		chart['series'] = series;
		chart['categories'] = categories;
		chart['yTitle'] = quotaDesc;

		$('#'+tabId+' #'+quotaCode+'_trend_chart').lineChart(chart);
	});
	
	//向后按钮
	$('a.nextMonth[data-quota]').on('click',function(){
		var quotaCode = $(this).attr('data-quota');
		var quotaDesc = $(this).attr('data-quotaDesc');
		var endIndex = $(this).attr('data-endIndex');
		
		var resultList = filterTrendCharts.resultList;
		var category = filterTrendCharts.categories;
		
		var totalMonthNum = category.length;//总月份数
		var startMonthIndex = 0;//起始下标
		var endMonthIndex = Number(endIndex);//结束下标
		
		//计算下标
		if(totalMonthNum>showNum){
			if(endMonthIndex == totalMonthNum){
				return;
			}else if(endMonthIndex + showNum >= totalMonthNum){
				endMonthIndex = totalMonthNum;
				startMonthIndex = endMonthIndex - showNum;
			} else {
				endMonthIndex += showNum;
				startMonthIndex = endMonthIndex - showNum;
			}
		}else {
			return;
		}
		
		//截取数组
		var chart = {};
		var series = [];
		$('#'+tabId+' a[data-endIndex][data-quota="'+quotaCode+'"]').attr('data-endIndex',endMonthIndex);
		var categories = category.slice(startMonthIndex,endMonthIndex);
		for (var i = 0; i < resultList.length; i++) {
			for ( var key in resultList[i]) {
				var monthData = resultList[i][key].slice(startMonthIndex,endMonthIndex);
				var data = [];
				for (var j = 0; j < monthData.length; j++) {
					data[j] = Number(monthData[j][quotaCode]);
				}
				series[i] = {name:key,data:data};
			}
		}
		
		chart['title'] = quotaDesc + '趋势图';
		chart['subtitle'] = categories[0].replace(/-0|-/,'年') +'月——'+ categories[categories.length-1].replace(/-0|-/,'年') +'月';
		chart['series'] = series;
		chart['categories'] = categories;
		chart['yTitle'] = quotaDesc;
		
		$('#'+tabId+' #'+quotaCode+'_trend_chart').lineChart(chart);
	})
}

//绑定图表上升下降等过滤的事件
function bindFilterEvent(charts,tables,trendChartData,compareText){
	//向前按钮
	$('.upDownFilter a').on('click',function(){
		var quotaCode = $(this).attr('data-quota');
		var quotaDesc = $(this).attr('data-quotaDesc');
		var filterType = $(this).attr('data-type');
		
		$('#'+tabId+' .upDownFilter a[data-quota="'+quotaCode+'"]').removeClass('curr');
		$(this).addClass('curr');
		
		var tempTables = tables;
		var tempCharts = charts;
		switch (filterType) {
		case 'top6'://前六
			var tempTrendChartData = {};
			tempTrendChartData = trendChartData;
			//按出院人数大小排序
			tempTables.sort(function(a,b){
				return b.TotalCaseCnt - a.TotalCaseCnt;
			})
			//截取前六
			if(tempTables.length > 6){
				tempTables = tempTables.slice(0,6);
			}
			reloadFilterChartsAndTables(tempCharts,tempTables,tempTrendChartData,quotaCode,quotaDesc,compareText,tabId);
			break;
		case 'up'://上升
			var tempTables1 = [];
			for (var i = 0; i < tables.length; i++) {
				if(tables[i][quotaCode] > tables[i]['compare'+quotaCode]){
					tempTables1.push(tables[i])
				}
			}
			reloadFilterChartsAndTables(tempCharts,tempTables1,trendChartData,quotaCode,quotaDesc,compareText,tabId);
			break;
		case 'down'://下降
			var tempTables1 = [];
			var tempTrendChartData = {};
			tempTrendChartData = trendChartData;
			for (var i = 0; i < tables.length; i++) {
				if(tables[i][quotaCode] < tables[i]['compare'+quotaCode]){
					tempTables1.push(tables[i])
				}
			}
			reloadFilterChartsAndTables(tempCharts,tempTables1,tempTrendChartData,quotaCode,quotaDesc,compareText,tabId);
			break;
		case 'all'://全部
			reloadFilterChartsAndTables(charts,tables,trendChartData,quotaCode,quotaDesc,compareText,tabId);
			break;
		}
		
		
		//$('#'+tabId+' #'+quotaCode+'_trend_chart').lineChart(chart);
	});
}

function reloadFilterChartsAndTables(tempCharts,tempTables,trendChartData,quotaCode,quotaDesc,compareText,tabId){
//	var functionName1 = "";
//	var functionName2 = "";
//	var functionName3 = "";
//	var operIcon = "";
	var mrType = $('#'+tabId+' #mrType').val()
	if (mrType=='MC') {
		showOrNot = false;
	} else {
		showOrNot = true;
	}
	if(tempCharts['chart_'+quotaCode]==undefined) return;
	//1.删除多余数据
	//
	var thisChart = {};
	var chart = tempCharts['chart_'+quotaCode].chart;
	var title = tempCharts['chart_'+quotaCode].title;
	var yAxis = tempCharts['chart_'+quotaCode].yAxis;
	var thisCategories = [];
	var thisSeries = [];
	for (var k = 0; k < tempCharts['chart_'+quotaCode].series.length; k++) {
		thisSeries[k] = {name:tempCharts['chart_'+quotaCode].series[k].name};
		var data = [];
		for (var j = 0; j < tempCharts['chart_'+quotaCode].xAxis.categories.length; j++) {
			for (var i = 0; i < tempTables.length; i++) {
				if (tempCharts['chart_'+quotaCode].xAxis.categories[j].key == tempTables[i].ccode ||
						tempCharts['chart_'+quotaCode].xAxis.categories[j].key == tempTables[i].ddesc) {
					thisCategories.push(tempCharts['chart_'+quotaCode].xAxis.categories[j])
					data.push(tempCharts['chart_'+quotaCode].series[k].data[j])
				}
			}
		}
		thisSeries[k]['data'] = data;
	}
	thisChart['chart'] = chart;
	thisChart['series'] = thisSeries;
	thisChart['xAxis'] = {categories: thisCategories};
	thisChart['title'] = title;
	thisChart['yAxis'] = yAxis;
	
	filterCharts['chart_'+quotaCode] = thisChart;
	
	//趋势图
	var thisResultList = [];
	var thisCategories = trendChartData.categories;
	for (var j = 0; j < trendChartData.resultList.length; j++) {
		for (var i = 0; i < tempTables.length; i++) {
			for ( var key in trendChartData.resultList[j]) {
				if (key == tempTables[i].ddesc || key == tempTables[i].ccode) {
					thisResultList.push(trendChartData.resultList[j]);//添加元素;
				}
			}
		}
	}
	
	var thisTrendChartData = {resultList:thisResultList,categories:thisCategories};
	filterTrendCharts = thisTrendChartData;
	//2.以下开始加载数据
	//
	$('#'+tabId+' #'+quotaCode+'_trend_chart').html('');
	loadTrendCharts(thisTrendChartData,quotaCode,quotaDesc);
	
	$('#'+tabId+' #'+quotaCode+'_compare_chart').html('');
	var chartType = $('#'+tabId+' #'+quotaCode+'_compare_chart').prev('div.chart-button').find('a.curr').attr('data-chart');
	 //加载默认图表
	 switch (chartType) {
	 case 'lineChart':
		 $('#'+tabId+' #'+quotaCode+'_compare_chart').lineChart(thisChart);
		 break;
	 case 'columnChart':
		 $('#'+tabId+' #'+quotaCode+'_compare_chart').columnChart(thisChart);
		 break;
	 case 'webChart':
		 $('#'+tabId+' #'+quotaCode+'_compare_chart').webChart(thisChart);
		 break;
	 case 'pieChart':
		 $('#'+tabId+' #'+quotaCode+'_compare_chart').pieChart(thisChart);
		 break;
	 case 'areaChart':
		 $('#'+tabId+' #'+quotaCode+'_compare_chart').areaChart(thisChart);
		 break;
	 case 'barChart':
		 $('#'+tabId+' #'+quotaCode+'_compare_chart').barChart(thisChart);
		 break;
	 default :
		 $('#'+tabId+' #'+quotaCode+'_compare_chart').barChart(thisChart);
	 	 break;
	 }
	
	//加载表格
	
	var idC = quotaCode + new Date().getTime();
	var tTitle = $('#'+tabId+' #'+quotaCode+'_compare_table table>thead>tr>td').first().text();
	
	if($('#'+tabId+' #'+quotaCode+'_compare_table table>tbody>tr').first().find('td').last().find('a').html()!=undefined){
		var index1 = $('#'+tabId+' #'+quotaCode+'_compare_table table>tbody>tr').first().find('td').first().html().indexOf('a');
		if(index1>0){
			functionName1 = $('#'+tabId+' #'+quotaCode+'_compare_table table>tbody>tr').first().find('td').first().html().replace(/<a.*javascript:(.*?)\(.*a>/g,'$1');
		}else{
			functionName1 = "";
		}
		functionName2 = $('#'+tabId+' #'+quotaCode+'_compare_table table>tbody>tr').first().find('td').last().find('a').eq(0).attr('href').replace(/javascript:(.*?)\(.*/g,'$1');
		functionName3 = $('#'+tabId+' #'+quotaCode+'_compare_table table>tbody>tr').first().find('td').last().html().replace(/<a.*javascript:(.*?)\(.*a>/g,'$1');
		operIcon = $('#'+tabId+' #'+quotaCode+'_compare_table table>tbody>tr').first().find('td').last().find('a').html();
	}
//	var functionName1 = $('#'+tabId+' #'+quotaCode+'_compare_table table>tbody>tr').first().find('td').first().html().replace(/<a.*javascript:(.*?)\(.*a>/g,'$1');
//	var functionName2 = $('#'+tabId+' #'+quotaCode+'_compare_table table>tbody>tr').first().find('td').last().html().replace(/<a.*javascript:(.*?)\(.*a>/g,'$1');
//	var operIcon = $('#'+tabId+' #'+quotaCode+'_compare_table table>tbody>tr').first().find('td').last().find('a').html();
	$('#'+tabId+' #'+quotaCode+'_compare_table').html('<h5 style="text-align:center;">'+tTitle+quotaDesc+'比较结果</h5>'
			+'<table id="'+idC+'" class="stripe cc table" style="width:100%;">'
			+'<thead><tr>'
			+'<td>'+tTitle+'</td>'
			+'<td>本期值</td>'
			+'<td>'+compareName+'值</td>'
			+'<td>累计值</td>'
			+'<td>'+compareName + compareText+'</td>'
			+'<td>累计'+ compareText +'</td>'
			+'<td>操作</td>'
			+'</tr></thead><tbody></tbody></table>');
	var columns=[ 
                 { "data": "DepGroup",
					   "orderData":[0,1],
					   "className":"depGroup",
              	   "render": function(obj, type, full) {
              		   if(functionName1){
              			   return "<a href=\"javascript:"+functionName1+"('"+full.ccode+"','"+full.ddesc+"') \">"+full.ddesc+"</a>";
              		   }
              		   return "("+full.ccode+")"+full.ddesc;
              	 	}
                   },
                   { "data": quotaCode},
                   { "data": 'compare'+quotaCode },
                   { "data": 'mc'+quotaCode ,'visible':showOrNot},
                   { "data": 'compare',
                       "render": function(obj, type, full) {
                    	    if (compareText == '增长量') {
                    	    	return compareValueGrowNum(full[quotaCode],full['compare'+quotaCode])
							} else {
								return compareValueGrowPer(full[quotaCode],full['compare'+quotaCode])
							}
		      	          	
	                    }
                   },
                   { "data": 'mc',
                       "render": function(obj, type, full) {
	                    	    if (compareText == '增长量') {
	                    	    	return compareValueGrowNum(full[quotaCode],full['mc'+quotaCode])
								} else {
									return compareValueGrowPer(full[quotaCode],full['mc'+quotaCode])
								}
	  	                    },
	  	                    'visible':showOrNot
                     },//累计增长量/率
                     { "data": "OPER" ,
                       "render": function(obj, type, full) {
                    	   if(functionName2==functionName3){
                    		 return "<a title='病例' href=\"javascript:"+functionName3+"('"+full.ccode+"','"+full.ddesc+"')\"><i class='fa fa-users'></i></a>"
                    	   }
	      	          	return "<a href=\"javascript:"+functionName2+"('"+full.ccode+"','"+full.ddesc+"') \">"+operIcon+"</a>"
	      	          +"<a title='病例' href=\"javascript:"+functionName3+"('"+full.ccode+"','"+full.ddesc+"')\"><i class='fa fa-users'></i></a>"
                         }
                   }
               ];
	var paramsDataTables={lengthChange:false,info:false,searching:false,stataSave:true,rownumbers:true,order:[ [ 2, "asc" ]],columnDefs:[ { "orderable": false, "targets": [5 ] }]};
	$("#"+tabId+" #"+idC).dataTableBasic(columns,tempTables,paramsDataTables);
}
//展开收起
function heightMore(){
	if($('#'+tabId+' #upDown').css('height')=='105px'){
		$('#'+tabId+' #upDown').css({'height':'auto','border-bottom-color':'#fff','overflow-y':'visible'});
	}else {
		$('#'+tabId+' #upDown').css({'height':'105px','border-bottom-color':'#ddd','overflow-y':'hidden'});
	}
}